<?php
/**
 * 保存栏目模块
 * @author jonwang
 */
class Model_Category_Save extends Model_CMS
{
    /**
     * 添加栏目
     *
     * @param array $data
     * @return ORM_Category_Data
     */
    public function add($data)
    {
        $orm_category = new ORM_Category_Finder();
        # 创建栏目
        $category = $orm_category->create();
        $this->save($category, $data);

        return $category;
    }

    /**
     * 修改栏目
     *
     * @param array $data
     * @return ORM_Category_Data
     */
    public function edit($data)
    {
        if (!$data['id']>0)
        {
            throw new Exception('请指定栏目ID', -1);
        }
        $orm_category = new ORM_Category_Finder();
        $category = $orm_category->get_by_id($data['id']);
        if (!$category)
        {
            throw new Exception('指定的栏目ID不存在', -1);
        }
        $this->save($category, $data);

        return $category;
    }

    /**
     * 保存栏目设置
     *
     * @param ORM_Category_Data $category
     * @param array $data
     * @throws Exception
     */
    protected function save(ORM_Category_Data $category,$data)
    {
        # 基本信息
        $this->set_data_base($category, $data);

        # 栏目封面设置
        $this->set_data_cover($category, $data['cover']);

        # 栏目列表设置
        $this->set_data_list($category->list, $data['list']);

        # 栏目SEO设置
        $this->set_data_seo($category, $data['seo']);

        # 执行保存动作
        $this->do_save($category);
    }

    /**
     * 保存栏目数据
     *
     * @param array $data
     */
    protected function do_save(ORM_Category_Data $category)
    {
        if ($category->id>0)
        {
            # 更新
            $category->update();
        }
        else
        {
            # 插入
            $category->insert();
        }
    }

    /**
     * 栏目基本信息
     *
     * @param ORM_Category_Data $category
     * @param array $data
     */
    protected function set_data_base(ORM_Category_Data $category , $data)
    {
        # 栏目名称
        if ( empty($data['cat_name']) )
        {
            throw new Exception('栏目名称不能空',-1);
        }
        $category->cat_name = $data['cat_name'];

        # 栏目域名
        if ( $data['domain'] && !preg_match('#^[a-z0-9\.\-]$#i', $data['domain']) )
        {
            throw new Exception('域名不符合要求，只能是数字字母和-');
        }

        # 栏目域名
        $category->domain = $data['domain'];

        # 栏目路径
        if ( $data['path'] && !preg_match('#^[a-z0-9\_]$#i', $data['path']) )
        {
            throw new Exception('栏目目录不符合要求，只能是数字字母和_');
        }
        $category->path = $data['path'];

        # 父栏目目录
        $category->parent_path = $data['parent_path']?1:0;

        $category->parent_cid = (int)$data['parent_cid'];
        if (!$data['parent_cid']>0)
        {
            $category->parent_cid = 0;
        }

        # 检查栏目
        if ($data['parent_cid']>0)
        {
            $orm_category = new ORM_Category_Finder();
            $parent_category = $orm_category->get_by_id($data['parent_cid']);
            if (!$parent_category)throw new Exception('指定的栏目不存在，请重新选择');

            if ( $category->id )
            {
                # 获取$parent_category所有的父栏目ID
                $all_ids = $parent_category->get_all_parent_category_ids();
                if ( is_array($all_ids) && in_array($category->id, $all_ids) )
                {
                    # 修改栏目需要检查下当前栏目是否为本栏目的子栏目，否则乱套了
                    throw new Exception('指定的父栏目为当前的子栏目，不可设置', -1);
                }
            }
            $category->parent_cid = $data['parent_cid'];
        }
        else
        {
            $category->parent_cid = 0;
        }
    }

    /**
     * 栏目封面设置
     *
     * @param array $data
     */
    protected function set_data_cover(ORM_Category_Data $category , $data)
    {
        if (!is_array($category->cover))
        {
            $category->cover = array();
        }
        $cover = $category->cover;

        if ( $data['use']!=1 )
        {
            # 未启用封面
            $cover['use'] = 0;
            return;
        }
        else
        {
            $cover['use'] = 1;
        }

        if (!$data['tpl'])
        {
            # 未选择模板
            throw new Exception('请选择封面模板',-1);
        }
        //TODO 检查模板是否有效

        # 封面生成静态页
        if ($data['tohtml'])
        {
            $cover['tohtml'] = 1;
            # 文件名称
            if ($data['filename'])
            {
                # 检查文件名是否符合要求
                $pos = strrpos($data['filename'],'.');
                if (false===$pos)
                {
                    $data['filename'] .= '.html';
                }
                else
                {
                    # 允许的后缀
                    $allow_suffix = Core::config('category/cover.allow_suffix');
                    if ($allow_suffix)
                    {
                        $suffix = substr($data['filename'],-$pos);
                        if ( !in_array($suffix, $allow_suffix) )
                        {
                            throw new Exception('指定的封面页后缀不符合要求',-1);
                        }
                    }
                }
            }
            else
            {
                $data['filename'] = 'index.html';
            }

            # 设置模板
            $cover['filename'] = $data['filename'];

            # 是否隐藏文件名
            $cover['hidden_filename'] = $data['hidden_filename']?1:0;
        }
        else
        {
            $cover['tohtml'] = 0;
            $cover['cache_time'] = (int)$data['cache_time'];
        }

        $category->cover = $cover;
    }

    /**
     * 栏目列表设置
     *
     * @param ORM_Category_Data_List $setting
     * @param array $data
     */
    protected function set_data_list(ORM_Category_Data_List $list_setting , $data)
    {
        if ( $data['use']!=1 )
        {
            # 未启用封面
            $list_setting->use = false;
            return;
        }

        if (!$data['tpl'])
        {
            # 未选择模板
            throw new Exception('请选择列表模板',-1);
        }
        $list_setting->tpl = $data['tpl'];

        # 每页显示数
        $data['limit'] = (int)$data['limit'];
        if (!$data['limit']>0)$data['limit'] = 30;    // 默认值
        $list_setting->limit = $data['limit'];

        # 最大页码
        $list_setting->maxpage = (int)$data['maxpage'];

        # 方式排序
        $list_setting->order_by = array(
            (string)$data['order_by'][0],
            $data['order_by'][1] == 'ASC'?'ASC':'DESC',
        );

        # 生成HTML
        if ($data['tohtml'])
        {
            $list_setting->tohtml = 1;
            # 文件名
            if ( $data['filename'] )
            {
                $list_setting->filename = $data['filename'];
            }
            else
            {
                $list_setting->filename = 'list_{{page}}.html';
            }

            $list_setting->tohtml_maxpage = (int)$data['tohtml_maxpage'];
        }
        else
        {
            $list_setting->tohtml = 0;
            # 缓存时间
            $list_setting->cache_time = (int)$data['cache_time'];
        }
    }

    /**
     * 栏目SEO设置
     *
     * @param ORM_Category_Data $category
     * @param array $data
     */
    protected function set_data_seo(ORM_Category_Data $category , $data)
    {
        # 标题
        $category->seo['title'] = $data['title'];

        # 关键词
        $category->seo['keyword'] = $data['keyword'];

        # 说明
        $category->seo['description'] = $data['description'];
    }
}